package cc.javaee.bbs.service.activity;

import cc.javaee.bbs.constants.Constants;
import cc.javaee.bbs.dao.BankuaiDao;
import cc.javaee.bbs.dao.TieziDao;
import cc.javaee.bbs.dao.activity.*;
import cc.javaee.bbs.exception.ResultException;
import cc.javaee.bbs.model.Huifu;
import cc.javaee.bbs.model.KbrPrizeCustomer;
import cc.javaee.bbs.model.PageBean;
import cc.javaee.bbs.model.Tiezi;
import cc.javaee.bbs.model.activity.*;
import cc.javaee.bbs.params.BizOutMap;
import cc.javaee.bbs.params.DbResultMap;
import cc.javaee.bbs.params.WebParams;
import cc.javaee.bbs.request.KoboroRequest;
import cc.javaee.bbs.service.HuifuService;
import cc.javaee.bbs.tool.DataFormatUtil;
import cc.javaee.bbs.tool.DateUtil;
import cc.javaee.bbs.vo.RankingVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ActivityService {

    @Autowired
    ActivityDao activityDao;
    @Autowired
    ActivityPrizeDao activityPrizeDao;
    @Autowired
    ActivityArrangeDao activityArrangeDao;
    @Autowired
    ActivityFileDao activityFileDao;
    @Autowired
    ActivityCustomerDao activityCustomerDao;
    @Autowired
    PrizeCustomerDao prizeCustomerDao;
    @Autowired
    TieziDao tieziDao;
    @Autowired
    DynamicCommentDao dynamicCommentDao;
    @Autowired
    HuifuService huifuService;
    @Autowired
    BankuaiCustomerDao bankuaiCustomerDao;
    @Autowired
    BankuaiDao bankuaiDao;

    public PageBean<KbrActivity> findpage(KbrActivity KbrActivity, PageBean<KbrActivity> page) {
        page.setBean(KbrActivity);
        int count = activityDao.findpagecount(page);
        page.setTotalRecords(count);
        List<KbrActivity> list = activityDao.findpage(page);
        page.setList(list);
        return page;
    }

    public KbrActivity findById(KbrActivity activity) {
        List<KbrActivity> list = activityDao.find(activity);
        if (list.size() > 0) {
            activity = list.get(0);
            Integer id = activity.getId();
            KbrActivityPrize prize = new KbrActivityPrize();
            prize.setActId(id);
            List<KbrActivityPrize> prizeList = new ArrayList<KbrActivityPrize>();
            prizeList = activityPrizeDao.find(prize);
            activity.setPrizeList(prizeList);

            KbrActivityArrange arranage = new KbrActivityArrange();
            arranage.setActId(id);
            List<KbrActivityArrange> arrangeList = new ArrayList<KbrActivityArrange>();
            arrangeList = activityArrangeDao.find(arranage);
            activity.setArrangeList(arrangeList);

            KbrActivityFile fileAct = new KbrActivityFile();
            fileAct.setActId(id);
            fileAct.setType("活动图片");
            List<KbrActivityFile> actFileList = new ArrayList<KbrActivityFile>();
            actFileList = activityFileDao.selectList(fileAct);
            activity.setActFileList(actFileList);

            KbrActivityFile fileAd = new KbrActivityFile();
            fileAd.setActId(id);
            fileAd.setType("广告图片");
            List<KbrActivityFile> adFileList = new ArrayList<KbrActivityFile>();
            adFileList = activityFileDao.selectList(fileAd);
            activity.setAdFileList(adFileList);


        }
        return activity;
    }


    public BizOutMap findDbList(WebParams param) throws ParseException {
        BizOutMap out = new BizOutMap();
        List<DbResultMap> list = activityDao.findDbList(param);
        if (list.size() > 0) {
            for (DbResultMap db : list) {
                Integer id = db.getInteger("id");
                String status = db.getString("status") + "";
//						;//尚未开始，正在进行，手动结束，已结束
                KbrActivityFile file = new KbrActivityFile();
                file.setActId(id);
                List<KbrActivityFile> kbrActivityFiles = activityFileDao.find(file);
                if (kbrActivityFiles != null && kbrActivityFiles.size() > 0) {
                    file = kbrActivityFiles.get(0);
                }
                db.put("imageUrl", file.getFilePath());
                if (status.equals("尚未开始")) {
                    db.put("imageUrl", file.getFilePath());
                    Long abDayNum = DateUtil.abDayNum(db.getString("startTimeStr"));
                    db.put("abDayNum", abDayNum);
                }
            }
        }
        out.put("actList", list);
        return out;
    }

    public BizOutMap findDb(WebParams param) throws ParseException {
        BizOutMap out = new BizOutMap();
        DbResultMap dbInfo = activityDao.findDb(param);
        if (dbInfo != null) {
            Integer id = dbInfo.getInteger("id");
            String status = dbInfo.getString("status") + "";
            KbrActivityFile file = new KbrActivityFile();
            file.setActId(id);
            List<KbrActivityFile> fileList = activityFileDao.find(file);
            dbInfo.put("imageUrl", file.getFilePath());
            dbInfo.put("fileList", fileList);
            if (status.equals("尚未开始")) {
                Long abDayNum = DateUtil.abDayNum(dbInfo.getString("startTimeStr"));
                dbInfo.put("abDayNum", abDayNum);
            }
            KbrActivityPrize prize = new KbrActivityPrize();
            prize.setActId(id);
            List<KbrActivityPrize> prizeList = new ArrayList<KbrActivityPrize>();
            prizeList = activityPrizeDao.find(prize);
            dbInfo.put("prizeList", prizeList);

            KbrActivityArrange arranage = new KbrActivityArrange();
            arranage.setActId(id);
            List<KbrActivityArrange> arrangeList = new ArrayList<KbrActivityArrange>();
            arrangeList = activityArrangeDao.find(arranage);
            dbInfo.put("arrangeList", arrangeList);
            if (status.equals("已结束")) {
                param.clear();
                param.put("actId", id);
                List<DbResultMap> prizeCustomerList = new ArrayList<DbResultMap>();
                prizeCustomerList = prizeCustomerDao.findDb(param);
                dbInfo.put("prizeCustomerList", prizeCustomerList);
            }

            if (status.equals("正在进行")) {
                param.clear();
                param.put("actId", id);
                List<DbResultMap> prizeCustomerList = new ArrayList<DbResultMap>();
                prizeCustomerList = prizeCustomerDao.findDb(param);
                dbInfo.put("prizeCustomerList", prizeCustomerList);

                param.clear();
                param.put("actId", id);
                List<DbResultMap> dynamicCommonList = new ArrayList<DbResultMap>();
                dynamicCommonList = dynamicCommentDao.findDbList(param);
                dbInfo.put("prizeCustomerList", prizeCustomerList);

            }

        }
        out.put("dbInfo", dbInfo);
        return out;
    }


    /**
     * 正在进行的活动详情的接口
     *
     * @param param
     * @return
     */
    public BizOutMap dbInfoIng(WebParams param) {
        BizOutMap out = new BizOutMap();
        return out;
    }

    public int signUp(Integer actId, String archivalNumber) throws ResultException {
        //添加报名用户
        Map customer = KoboroRequest.getCustomer(archivalNumber);
        if (MapUtils.isEmpty(customer)) {
            throw new ResultException(-1, "报名用户不存在");
        }
        Date now = new Date();
        KbrActivityCustomer kac = new KbrActivityCustomer();
        kac.setActId(actId);
        kac.setArchivalNumber(archivalNumber);
        // 添加获取参与人员
        List<KbrActivityCustomer> list = activityCustomerDao.find(kac);
        if (CollectionUtils.isNotEmpty(list)) {
            throw new ResultException(-1, "已经报名");
        }
        kac.setImgPath((String) customer.get("imgFullPath"));
        kac.setCustId((Integer) customer.get("id"));
        kac.setCreateTime(now);
        kac.setCustName((String) customer.get("name"));

        KbrActivity params = new KbrActivity();
        params.setId(actId);
        List<KbrActivity> activities = activityDao.find(params);
        KbrActivity activity = null;
        if (CollectionUtils.isNotEmpty(activities)) {
            activity = activities.get(0);
        }
        if (activity == null) {
            throw new ResultException(-1, "活动不存在");
        }

        // 获取板块信息
//        Bankuai bankuaiParam = new Bankuai();
//        bankuaiParam.setId(activity.getBankuaiId());
//        Bankuai bankuai = null;
//        List<Bankuai> bankuaiList = bankuaiDao.select(bankuaiParam);
//        if (CollectionUtils.isNotEmpty(bankuaiList)) {
//            bankuai = bankuaiList.get(0);
//        }

        BankuaiCustomer bankuaiCustomer = new BankuaiCustomer();
        bankuaiCustomer.setBankuaiId(activity.getBankuaiId());
        bankuaiCustomer.setArchivalNumber(archivalNumber);

        List<BankuaiCustomer> bankuaiCustomers = bankuaiCustomerDao.find(bankuaiCustomer);
        if (CollectionUtils.isEmpty(bankuaiCustomers)) {

            bankuaiCustomer.setCreateTime(now);
            bankuaiCustomer.setImgPath((String) customer.get("imgFullPath"));
            bankuaiCustomer.setCustName((String) customer.get("name"));
            bankuaiCustomer.setCustId((Integer) customer.get("id"));
            if (Constants.KOBORO_ACTIVITY_TYPE.equals(activity.getType())) {
                bankuaiCustomer.setBankuaiId(Constants.KOBORO_ACTIVE_BANKUAIID);
            } else {
                bankuaiCustomer.setBankuaiId(Constants.COMPANY_ACTIVE_BANKUAIID);
            }

            bankuaiCustomerDao.insert(bankuaiCustomer);
        }
//        kac.setCustId();
//        kac.setImgPath();

        return activityCustomerDao.insert(kac);
    }

    public List<KbrActivityCustomer> findCustomer(Integer actId, String archivalNumber) {
        KbrActivityCustomer kac = new KbrActivityCustomer();
        kac.setActId(actId);
        kac.setArchivalNumber(archivalNumber);
        List<KbrActivityCustomer> list = activityCustomerDao.find(kac);
        return list;
    }

    /**
     * 保存活动信息
     *
     * @param params
     * @return
     */
    public BizOutMap saveActivity(WebParams params) {
        KbrActivity activity = (KbrActivity) params.get("activity");
        Integer id = activity.getId();
        Date enStartTime = DataFormatUtil.toDateTimeFromStr(activity.getEnStartTimeStr());
        Date enEndTime = DataFormatUtil.toDateTimeFromStr(activity.getEnEndTimeStr());
        Date startTime = DataFormatUtil.toDateTimeFromStr(activity.getStartTimeStr());
        Date endTime = DataFormatUtil.toDateTimeFromStr(activity.getEndTimeStr());
//        activity.setSignStatus("尚未开始报名");
//        activity.setStatus("尚未开始");
        activity.setSignStatus(0);
        activity.setStatus(0);
        activity.setCreateTime(new Date());
        activity.setAlreadyCount(0);
        activity.setEnStartTime(enStartTime);
        activity.setEnEndTime(enEndTime);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);

        if (id != null) {
            activityDao.update(activity);
        } else {
            activityDao.insert(activity);
        }

        Integer idNow = activityDao.getMaxId(null);
        params.put("actId", idNow);
        params.put("actName", activity.getName());
        // 设置奖项
        savePrize(params);
        // 设置流程
        saveArrave(params);
        // 设置图片
        saveImg(params);
//        saveCricle(params);
        // 保存话题（帖子）
        saveTopic(params);
        return null;

    }

    public void savePrize(WebParams params) {
        Integer actId = params.getInteger("actId");
        activityPrizeDao.deleteByActId(actId);
        String[] prizeName = (String[]) params.get("prizeName");
        String[] prizeCount = (String[]) params.get("prizeCount");
        String[] prizeContent = (String[]) params.get("prizeContent");

        if (prizeName != null && prizeName.length > 1) {
            for (int i = 0; i < prizeName.length; i++) {
                KbrActivityPrize prize = new KbrActivityPrize();
                prize.setActId(actId);
                prize.setName(prizeName[i]);
                prize.setCount(Integer.parseInt(prizeCount[i]));
                prize.setPrize(prizeContent[i]);
                activityPrizeDao.insert(prize);
            }
        }
    }

    public void saveArrave(WebParams params) {
        Integer actId = params.getInteger("actId");
        activityArrangeDao.deleteByActId(actId);
        String[] arrangeName = (String[]) params.get("arrangeName");
        String[] arrangeStartTime = (String[]) params.get("arrangeStartTime");
        String[] arrangeEndTime = (String[]) params.get("arrangeEndTime");

        if (arrangeName != null && arrangeName.length > 1) {
            for (int i = 0; i < arrangeName.length; i++) {
                Date startTime = DataFormatUtil.toDateTimeFromStr(arrangeStartTime[i]);
                Date endTime = DataFormatUtil.toDateTimeFromStr(arrangeEndTime[i]);
                KbrActivityArrange arrange = new KbrActivityArrange();
                arrange.setActId(actId);
                arrange.setName(arrangeName[i]);
                arrange.setStartTime(startTime);
                arrange.setEndTime(endTime);
                arrange.setStatus("未开始");
                activityArrangeDao.insert(arrange);
            }
        }
    }

    public void saveImg(WebParams params) {

        Integer actId = params.getInteger("actId");
        activityFileDao.deleteByActId(actId);


        String[] actImg = (String[]) params.get("actImg");
        String[] adImg = (String[]) params.get("adImg");
        if (actImg != null && actImg.length > 0) {
            for (int i = 0; i < actImg.length; i++) {
                KbrActivityFile file = new KbrActivityFile();
                file.setActId(actId);
                file.setFileName("活动图片");
                file.setFilePath(actImg[i]);
                file.setType("活动图片");
                file.setStatus("有效");
                activityFileDao.insert(file);
            }
        }
        if (adImg != null && adImg.length > 0) {
            for (int i = 0; i < adImg.length; i++) {
                KbrActivityFile file = new KbrActivityFile();
                file.setActId(actId);
                file.setFileName("广告图片");
                file.setFilePath(adImg[i]);
                file.setType("广告图片");
                file.setStatus("有效");
                activityFileDao.insert(file);
            }
        }
    }

//    public void saveCricle(WebParams params) {
//        Integer actId = params.getInteger("actId");
//        String actName = params.getString("actName");
//        KbrCircle circle = new KbrCircle();
//        circle.setActId(actId);
//        circle.setName(actName);
//        circle.setContent(actName);
//        circle.setCreateTime(new Date());
//        circleDao.insert(circle);
//    }

    //创建话题（帖子）
    public void saveTopic(WebParams params) {
        Integer actId = params.getInteger("actId");
        KbrActivity activity = (KbrActivity) params.get("activity");
        String actName = params.getString("actName");
        Tiezi tiezi = new Tiezi();
        if (Constants.KOBORO_ACTIVITY_TYPE.equals(activity.getType())) {
            tiezi.setBankuaiId(Constants.KOBORO_ACTIVE_BANKUAIID);
        } else {
            tiezi.setBankuaiId(Constants.COMPANY_ACTIVE_BANKUAIID);
        }
        tiezi.setCreateuserid((Integer) params.get("userId"));
        tiezi.setZhutiid(actId);
        tiezi.setName(actName);
        tiezi.setContenthtml(activity.getDescriber());
        tiezi.setCreatetime(new Date());
        tieziDao.insert(tiezi);
    }

    //后台页面查询
    public BizOutMap findActInfo(String id) {
        // TODO Auto-generated method stub
        return null;
    }

    //	修改活动
    public BizOutMap updateActivity(KbrActivity activity) {
        activityDao.update(activity);
        return null;
    }


    //	修改活动
    public void updateStatus(KbrActivity activity) {
        activityDao.updateByDb(activity);
    }


    public void activityFinish(KbrActivity activity) {
        activity.setStatus(Constants.ActivityStatus.END);
        activityDao.update(activity);
        computingRankings(activity);
    }

    public Map<String, List<DbResultMap>> grouping(List<DbResultMap> oldList) {

        Map<String, List<DbResultMap>> result = new HashMap();
        for (DbResultMap e : oldList) {
            String status = e.getString("status");
            List list = null;
            if (result.containsKey(status)) {
                list = result.get(status);
            } else {
                list = new ArrayList();
                result.put(status, list);
            }
            list.add(e);
        }
//        Map<String, List<DbResultMap>> result = null;
//        if(oldList!=null && oldList.size()>0){
//            result = oldList.stream().collect(Collectors.groupingBy(e -> e.getString("status")));
//        }

        return result;
    }

    public List<KbrActivity> find(KbrActivity activity) {
        return activityDao.find(activity);
    }

    public KbrActivity findById(int id) {
        KbrActivity kbrActivity = new KbrActivity();
        kbrActivity.setId(id);
        List<KbrActivity> activities = find(kbrActivity);
        if (CollectionUtils.isNotEmpty(activities)) {
            KbrActivity activity = activities.get(0);
            KbrActivityArrange paramArrange = new KbrActivityArrange();
            paramArrange.setActId(activity.getId());
            List<KbrActivityArrange> kbrActivityArranges = activityArrangeDao.find(paramArrange);
            activity.setArrangeList(kbrActivityArranges);
            return activity;
        }
        return null;
    }

    /**
     * 计算排名发放奖励
     *
     * @param activity
     */
    public void computingRankings(KbrActivity activity) {
        KbrActivityCustomer customer = new KbrActivityCustomer();
        customer.setActId(activity.getId());
        // 获取参与人员
        List<KbrActivityCustomer> customers = activityCustomerDao.find(customer);

        if (Constants.TriggerType.UPLOAD_FILES.equals(activity.getTriggerType())) {
            // 为用户上传文件
            voteOrLike(activity, customers);
        } else {
            // 为系统监测
            systemCompute(activity, customers);
        }
    }

    private List<Huifu> uploadFilesHuifu(KbrActivity activity, List<KbrActivityCustomer> customers) {
        List<Integer> custIds = customers.stream().map(KbrActivityCustomer::getCustId).collect(Collectors.toList());

        // 获取参与话题
        Tiezi paramTiezi = new Tiezi();
        paramTiezi.setZhutiid(activity.getId());
        List<Tiezi> tiezis = tieziDao.findTiezi(paramTiezi);
        if (CollectionUtils.isEmpty(tiezis)) {
            return new ArrayList<>();
        }
        Tiezi tiezi = tiezis.get(0);

        // 获取参与者上传文件评论
        List<Huifu> huifus = huifuService.findByIds(tiezi.getId(), Constants.HuifuType.UPLOAD_FILES, custIds);

        return huifus;
    }

    public List<Huifu> huifuList(Integer actId, Integer type, List<KbrActivityCustomer> customers) {
        List<Integer> custIds = customers.stream().map(KbrActivityCustomer::getCustId).collect(Collectors.toList());

        // 获取参与话题
        Tiezi paramTiezi = new Tiezi();
        paramTiezi.setZhutiid(actId);
        List<Tiezi> tiezis = tieziDao.findTiezi(paramTiezi);
        if (CollectionUtils.isEmpty(tiezis)) {
            return new ArrayList<>();
        }
        Tiezi tiezi = tiezis.get(0);

        // 获取参与者上传文件评论
        List<Huifu> huifus = huifuService.findByIds(tiezi.getId(), type, custIds);

        return huifus;
    }

    // 给被投票 或者被点赞着发奖
    private void voteOrLike(KbrActivity activity, List<KbrActivityCustomer> customers) {
        // 获取文件上传用户排名
        List<Huifu> huifus = uploadFilesHuifu(activity, customers);

        //getLikeCount(getVoteCount) 取最大值 并根据(getVoteCount)getLikeCount排序
        Comparator<Huifu> comparator = (o1, o2) -> {
            if (Constants.RuleType.LIKE.equals(activity.getRuleType())) {
                return o1.getLikeCount() - o2.getLikeCount();
            } else {
                return o1.getVoteCount() - o2.getVoteCount();
            }
        };

        Map<Integer, KbrActivityCustomer> customerMap = customers.stream().collect(Collectors.toMap(KbrActivityCustomer::getCustId, cust -> cust));

        // 根据 getCreateuserid 去重
        // 同一个人的评论去重取最大的点赞数 或者 投票数
        List<KbrActivityCustomer> winners = huifus.stream()
                .collect(Collectors.groupingBy(Huifu::getCreateuserid))
                .values().stream().map(e ->
                        e.stream().max(comparator).get()
                ).sorted(comparator).map(e -> customerMap.get(e.getCreateuserid())).collect(Collectors.toList());

        //获取奖励
        List<KbrActivityPrize> prizes = getPrizes(activity.getId());

        //发送奖励
        prize(winners, prizes);
    }


    private void systemCompute(KbrActivity activity, List<KbrActivityCustomer> customers) {
        Map<String, KbrActivityCustomer> customerMap = customers.stream().collect(Collectors.toMap(KbrActivityCustomer::getArchivalNumber, cust -> cust));
        List<String> archivalNumbers = new ArrayList<>(customerMap.keySet());
        // TODO: 2018/5/26 调用接口 获取用户
        List<String> qualified = archivalNumbers;
        if (CollectionUtils.isEmpty(qualified)) {
            return;
        }

        List<KbrActivityCustomer> qualifiedCustomer = qualified.stream()
                .map(e -> customerMap.get(e)).filter(e -> e != null)
                .collect(Collectors.toList());

        //获取奖品
        List<KbrActivityPrize> prizes = getPrizes(activity.getId());

        //抽奖
        List<KbrActivityCustomer> winners = luckyDraw(qualifiedCustomer, prizes.size());

        //发奖
        prize(winners, prizes);

    }

    public List<KbrActivityCustomer> luckyDraw(List<KbrActivityCustomer> customers, int size) {
        List<KbrActivityCustomer> oldCustom = new ArrayList<KbrActivityCustomer>(customers);
        List<KbrActivityCustomer> winners = new ArrayList<KbrActivityCustomer>();

        if (CollectionUtils.isEmpty(oldCustom) || size <= 0) {
            return new ArrayList<>();
        }
        // 如果获奖名额大于获奖人数,获奖名额等于获奖人数
        if (size > oldCustom.size()) {
            size = oldCustom.size();
        }

        Random random = new Random();
        for (int i = 0; i < size; i++) {
            int winner = random.nextInt(oldCustom.size());
            winners.add(oldCustom.remove(winner));
        }
        return winners;
    }

    //根据活动ID 获取奖品
    public List<KbrActivityPrize> getPrizes(Integer actId) {
        // 获取奖品
        KbrActivityPrize paramPri = new KbrActivityPrize();
        paramPri.setActId(actId);
        List<KbrActivityPrize> prizes = activityPrizeDao.find(paramPri);
        //判断剩余奖品>0  根据剩余数量创建指定数量对象
        List<KbrActivityPrize> prizesFull = prizes.stream().filter(e -> e.remainingPrize() > 0).map(e -> e.batchCloneAndThis())
                .reduce((o1, o2) -> {
                    o1.addAll(o2);
                    return o1;
                }).get();
        prizesFull.sort((o1, o2) -> o1.getSort() - o1.getSort());
        return prizesFull;
    }

    //根据活动ID 获取奖品
    public List<KbrActivityPrize> getPrizesBreakp(Integer actId) {
        // 获取奖品
        KbrActivityPrize paramPri = new KbrActivityPrize();
        paramPri.setActId(actId);
        List<KbrActivityPrize> prizes = activityPrizeDao.find(paramPri);
        prizes.sort((o1, o2) -> o1.getSort() - o1.getSort());
        return prizes;
    }

    //发奖
    public void prize(List<KbrActivityCustomer> winners, List<KbrActivityPrize> prizes) {
        for (int i = 0; i < winners.size() && i < prizes.size(); ) {

            // 需要发奖励的用户
            KbrActivityCustomer winner = winners.get(i);

            // 奖励
            KbrActivityPrize prize = prizes.get(i);

            KbrPrizeCustomer prizeCustomer = new KbrPrizeCustomer();
            prizeCustomer.setActId(winner.getActId());
            prizeCustomer.setArchivalNumber(winner.getArchivalNumber());
            prizeCustomer.setCreateTime(new Date());
            prizeCustomer.setCustId(winner.getCustId());
            prizeCustomer.setPrizeId(prize.getId());
            prizeCustomer.setPrizeName(prize.getName());
            prizeCustomer.setRanking(++i);
            prizeCustomerDao.insert(prizeCustomer);
            //更新使用次数
            activityPrizeDao.updateUseCount(prize);
        }
    }


    /**
     * 随机指定范围内N个不重复的数
     * 在初始化的无重复待选数组中随机产生一个数放入结果中，
     * 将待选数组被随机到的数，用待选数组(len-1)下标对应的数替换
     * 然后从len-2里随机产生下一个随机数，如此类推
     *
     * @param max 指定范围最大值
     * @param min 指定范围最小值
     * @param n   随机数个数
     * @return int[] 随机数结果集
     */
    public static int[] randomArray(int min, int max, int n) {
        int len = max - min + 1;

        if (max < min || n > len) {
            return null;
        }

        //初始化给定范围的待选数组
        int[] source = new int[len];
        for (int i = min; i < min + len; i++) {
            source[i - min] = i;
        }

        int[] result = new int[n];
        Random rd = new Random();
        int index = 0;
        for (int i = 0; i < result.length; i++) {
            //待选数组0到(len-2)随机一个下标
            index = Math.abs(rd.nextInt() % len--);
            //将随机到的数放入结果集
            result[i] = source[index];
            //将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换
            source[index] = source[len];
        }
        return result;
    }


    public List<Huifu> huifuRanking(KbrActivity activity, List<KbrActivityCustomer> customers) {
        List<Huifu> huifus = uploadFilesHuifu(activity, customers);

        //getLikeCount(getVoteCount) 取最大值 并根据(getVoteCount)getLikeCount排序
        Comparator<Huifu> comparator = (o1, o2) -> {
            if (Constants.RuleType.LIKE.equals(activity.getRuleType())) {
                return o1.getLikeCount() - o2.getLikeCount();
            } else {
                return o1.getVoteCount() - o2.getVoteCount();
            }
        };

        // 根据 getCreateuserid 去重
        // 同一个人的评论去重取最大的点赞数 或者 投票数
        List<Huifu> ranking = huifus.stream()
                .collect(Collectors.groupingBy(Huifu::getCreateuserid))
                .values().stream().map(e -> e.stream().max(comparator).get()
                ).sorted(comparator).collect(Collectors.toList());
        return ranking;
    }

    public List<KbrPrizeCustomer> getPrizeCustomer(Integer actId) {
        KbrPrizeCustomer kbrPrizeCustomer = new KbrPrizeCustomer();
        kbrPrizeCustomer.setActId(actId);
        List<KbrPrizeCustomer> prizeCustomers = prizeCustomerDao.find(kbrPrizeCustomer);
        return prizeCustomers;
    }


    public RankingVO leaderboard(int actId, String archivalNumber) throws ResultException {
        // 获取当前用户
        BankuaiCustomer currentCustomer = bankuaiCustomerDao.getCustomerInfoByCustomerId(archivalNumber);
        //根据活动id查询话题
        List<KbrActivityCustomer> listCustomer = activityCustomerDao.findActivityCustomerByActid(actId);

        //排名集合
        List<Huifu> arrayList = new ArrayList<Huifu>();
        Integer rankNum = 0;//排名
        Integer voteCount = 0;//获得的投票数
        String name = "";//姓名
        String path = "";//头像
        Map<Integer, KbrActivityCustomer> mapCustomer = listCustomer.stream().collect(Collectors.toMap(KbrActivityCustomer::getCustId, e -> e));
        if (listCustomer != null && listCustomer.size() > 0) {
            //根据活动id查询话题
            List<Tiezi> listTieZi = tieziDao.findTieZiByActid(actId);
            if (listTieZi != null && listTieZi.size() > 0) {
                Tiezi tiezi = listTieZi.get(0);
                for (KbrActivityCustomer k : listCustomer) {
                    //根据帖子id和类型和用户id查询回复
                    List<Huifu> listHuifu = huifuService.getHuiFuByTieziidType(tiezi.getId(), 2, k.getCustId(), currentCustomer.getCustId());
                    if (listHuifu != null && listHuifu.size() > 0) {
                        Huifu huifu = listHuifu.stream().max((o1, o2) -> o1.getVoteCount().compareTo(o2.getVoteCount())).get();
                        //根据帖子id和类型和用户id查询投票数
//                        List<Huifu> listHuifuVote = huifuService.getHuiFuByTieziidType(tiezi.getId(), 3, k.getCustId());
//                        int myType = 0;
//                        if (listHuifuVote != null && listHuifuVote.size() > 0) {
//                            listHuifu.get(0).setVoteCount(listHuifuVote.size());
//                            long count = listHuifuVote.stream().filter(e -> currentCustomer.getCustId().equals(e.getCreateuserid())).count();
//                            if (count > 0) {
//                                myType = 1;
//                            }
//                        }
//                        listHuifu.get(0).setMyType(myType);
                        arrayList.add(huifu);
                    }
                }
                //进行排序
                Collections.sort(arrayList, (o1, o2) -> o1.getVoteCount().compareTo(o2.getVoteCount()));


                arrayList.stream().map(e -> {
                    KbrActivityCustomer customer = mapCustomer.get(e.getCreateuserid());
                    if (customer != null) {
                        e.setName(customer.getCustName());
                    }
                    return e;
                });
                // 获取本人排名
                for (int i = 0; i < arrayList.size(); i++) {
                    if (currentCustomer != null) {
                        Huifu huifu = arrayList.get(i);
                        if (huifu.getCreateuserid().equals(currentCustomer.getCustId())) {
                            rankNum = i + 1;
                            voteCount = huifu.getVoteCount();
                            name = currentCustomer.getCustName();
                            path = currentCustomer.getImgPath();
                        }
                    }
                }
            }
        }
        RankingVO vo = new RankingVO();
//		String data ="{\"list\":"+JsonUtil.objToJson(arrayList)+",\"rankNum\":"+rankNum+",\"voteCount\":"+voteCount+",\"name\":\""+name+"\",\"path\":\""+path+"\"}";
        vo.setList(arrayList);
        vo.setRankNum(rankNum);
        vo.setVoteCount(voteCount);
        vo.setName(name);
        vo.setPath(path);
        return vo;
    }

}
